package com.wl.dzt.sys.controller.action;

import com.wl.dzt.sys.controller.param.Param;
import com.wl.dzt.sys.controller.result.ActionResult;
import com.wl.dzt.sys.controller.result.FormResult;
import com.wl.dzt.sys.core.dao.DB;
import com.wl.dzt.sys.core.dao.curd.validate.Validate;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description 批量保存动作
 * 用于执行批量保存
 * 需要传递JSON适配器已保证数据结构的正确
 */
@Component
public class BatSaveAction implements Action {

    public ActionResult doAction(Param param) {
        ActionResult actionResult = new ActionResult();
        List list = new ArrayList();
        // 自定义适配
        if (param.getConvert() != null) {
            list.addAll(param.getData());
        }
        // 默认适配
        else {
            param.getData().forEach(map -> {
                try {
                    Object entity = param.getClazz().newInstance();
                    BeanMap row = BeanMap.create(entity);
                    row.putAll((Map) map);
                    list.add(entity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        FormResult formResult = new FormResult();
        formResult.setSuccess(DB.saves(list.toArray(), param.getValidates().toArray(new Validate[param.getValidates().size()])));
        actionResult.setFormResult(formResult);
        return actionResult;
    }

}
